package yxy.game.pm2.command.daliy;

import org.joda.time.DateTime;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TaskMessage;
import yxy.game.pm2.module.daily.DailyModule;
import yxy.game.pm2.module.task.TaskHandle;

import java.util.Map;

/** 任务成就 日常进度获取 */
@MessageType(proto = Command.DailyTaskProgressAcquire, classtype = TaskMessage.DailyTaskProgressAcquireRequest.class)
public class CMD_DailyTaskProgressAcquire extends Command<TaskMessage.DailyTaskProgressAcquireRequest> {

	@Override
	public void execute(MessageSource messageSource, TaskMessage.DailyTaskProgressAcquireRequest request) {
		String playerCode = messageSource.getTag();

		TaskMessage.DailyTaskProgressAcquireResponse.Builder response = TaskMessage.DailyTaskProgressAcquireResponse.newBuilder();

		DailyModule dailyModule = DailyModule.get(playerCode);

		response.setVitality(dailyModule.getExp());

		for (Integer levelRewardId : dailyModule.getLevelReward()) {
			response.addIds(levelRewardId);
		}
		Map<String, Task> allTask = Task.all(playerCode);
		for (String taskCode : dailyModule.getTaskCodes()) {
			Task task = allTask.get(taskCode);
			if (task == null) {
				continue;
			}
			response.addTasks(TaskHandle.packTask(task));
		}

		// 刷新时间
		DateTime now = DateTime.now();
		DateTime fresh = DateTime.now().plusDays(1).withTimeAtStartOfDay();
		response.setFreshtime(fresh.getMillis() - now.getMillis());

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, TaskMessage.DailyTaskProgressAcquireResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}